package com.bpf.base.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;


public class UploadFile {
	
	/**
	 * 文件上传
	 * @param file 前台文件
	 * @param name 存储名前缀
	 * @param request HttpServletRequest
	 * @return 数据库存储字段名：name+当前时间
	 */
	public static String loadPicture(MultipartFile file ,String name,HttpServletRequest request){
		/*
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		if (!file.isEmpty()) {
			byte[] bytes;
			try {
				bytes = file.getBytes();	
				
				String rootPath = request.getSession().getServletContext().getRealPath(Constants.FILE_DEFAULT_URL);
				File dir = new File(rootPath + File.separator);
				
				if (!dir.exists()) {
					dir.mkdirs();
				}
			//	String path=dir.getAbsolutePath() + File.separator + file.getOriginalFilename();		
				String[] t=file.getOriginalFilename().split("\\.");
				String pictureType=t[t.length-1];
				String pictureName=name+sdf.format(new Date())+"."+pictureType;
				String path=dir.getAbsolutePath() + File.separator +pictureName;
				
				File serverFile = new File(path);				
				BufferedOutputStream stream;				
				stream = new BufferedOutputStream(new FileOutputStream(serverFile));
				stream.write(bytes);
				stream.close();
				return pictureName;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println("FileLoad Error...:"+e.getMessage());
				}																	
		}
		return null;*/
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		
		if (!file.isEmpty()) {
			byte[] bytes;
			try {
				bytes = file.getBytes();
				
				//文件上传路径
				String rootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
				File dir = new File(rootPath + File.separator);
				
				System.out.println("上传路径 ="+dir.getPath());
				
				if (!dir.exists()) {
					dir.mkdirs();
				}
				
				String[] t=file.getOriginalFilename().split("\\.");
				String pictureType=t[t.length-1];
				String pictureName=name+sdf.format(new Date())+"."+pictureType;
				String path=dir.getAbsolutePath() + File.separator +pictureName;
				
				File serverFile = new File(path);				
				BufferedOutputStream stream;				
				stream = new BufferedOutputStream(new FileOutputStream(serverFile));
				stream.write(bytes);
				stream.close();
				System.out.println(pictureName);
				return pictureName;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println("FileLoad Error...:"+e.getMessage());
				}																	
		}
		return null;
	}
	
	public static String appLoadPicture(String file ,String name,HttpServletRequest request){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		if(file!=null){
			byte[] bytes;
			try {
				bytes =Base64Coder.decodeLines(file);;	
				
				String rootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
				File dir = new File(rootPath + File.separator);
				if (!dir.exists()) {
					dir.mkdirs();
				}
			//	String path=dir.getAbsolutePath() + File.separator + file.getOriginalFilename();
			
				String[] t=dir.getName().split("\\.");
				String pictureType=t[t.length-1];
				String pictureName=name+sdf.format(new Date())+"."+pictureType;
				String path=dir.getAbsolutePath() + File.separator +pictureName;
				System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+path);
				File serverFile = new File(path);				
				BufferedOutputStream stream;				
				stream = new BufferedOutputStream(new FileOutputStream(serverFile));
				stream.write(bytes);
				stream.close();
				return pictureName;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println("FileLoad Error...:"+e.getMessage());
				}																	
		}
		return null;
	}
	
	//上传文档
	public static String loadDoc(MultipartFile file ,String name,HttpServletRequest request){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		if (!file.isEmpty()) {
			byte[] bytes;
			try {
				bytes = file.getBytes();	
				
				String rootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/docment");
				File dir = new File(rootPath + File.separator);
				if (!dir.exists()) {
					dir.mkdirs();
				}
			//	String path=dir.getAbsolutePath() + File.separator + file.getOriginalFilename();
			
				String[] t=file.getOriginalFilename().split("\\.");
				String pictureType=t[t.length-1];
				String pictureName=name+sdf.format(new Date())+"."+pictureType;
				String path=dir.getAbsolutePath() + File.separator +pictureName;
				System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+path);
				File serverFile = new File(path);				
				BufferedOutputStream stream;				
				stream = new BufferedOutputStream(new FileOutputStream(serverFile));
				stream.write(bytes);
				stream.close();
				return pictureName;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println("FileLoad Error...:"+e.getMessage());
				}																	
		}
		return null;
	}
	
	//下载文档
	public static String downDoc(final HttpServletRequest request, String filePath, String fileName, final HttpServletResponse response) throws Exception{
		 
        java.io.BufferedInputStream bis = null;  
        java.io.BufferedOutputStream bos = null;  
        String ctxPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/docment")+ "\\";  
        String downLoadPath = ctxPath + filePath; 
        String [] filePaths = filePath.split("\\.");
        String docName = fileName+"."+filePaths[1];
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+downLoadPath);  
        try {  
            long fileLength = new File(downLoadPath).length();  
            response.setContentType("application/x-msdownload;");  
            response.setHeader("Content-disposition", "attachment; filename="  
                    + new String(docName.getBytes("utf-8"), "ISO8859-1"));  
            response.setHeader("Content-Length", String.valueOf(fileLength));  
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
            bos = new BufferedOutputStream(response.getOutputStream());  
            byte[] buff = new byte[2048];  
            int bytesRead;  
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
                bos.write(buff, 0, bytesRead);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bis != null)  
                bis.close();  
            if (bos != null)  
                bos.close();  
        }  
        return null;
	}
}
